// Learn TypeScript:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/typescript.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/life-cycle-callbacks.html
import world from './world';
import Loading from './Loading';
const { ccclass, property } = cc._decorator;
//console.log(loading)
@ccclass
export default class NewClass extends cc.Component {

    @property({
        displayName: "动画Node",
        type: cc.Node,
    })
    mcNode: cc.Node = null;

    @property({
        displayName: "地图Node",
        type: cc.Node,
    })
    mapNode: cc.Node = null;

    @property({
        displayName: "速度",
        tooltip: '移动的速度，值越大跑的越快'
    })
    speed: number = 3;

    @property({
        displayName: "弹跳力",
        tooltip: '跳起的力量，如果重量不变，值越大跑的越高'
    })
    bounce: number = 15;




    @property({ type: cc.AudioClip })
    jumpSou: cc.AudioClip = null;

    @property({ type: cc.Node })
    jbMC: cc.Node = null;


    // LIFE-CYCLE CALLBACKS:

    private keyArr: Array<string> = [];
    private anim: cc.Animation;
    private mc: dragonBones.ArmatureDisplay;
    private map: any;
    private jbArr;
    private loading: Loading;
    onLoad() {
        cc.director.getCollisionManager().enabled = true;
        //cc.director.getCollisionManager().enabledDebugDraw=true;
        this.keyArr = [];
        this.loading = new Loading();
        this.jbMC.parent = null;
        this.jbArr = [this.jbMC];
        cc['eventManager'].addListener({
            event: cc['EventListener'].KEYBOARD,
            onKeyPressed: this.onKeyPressed.bind(this),
            onKeyReleased: this.onKeyReleased.bind(this)
        }, this.node);
        this.anim = this.mcNode.getComponent(cc.Animation);
        window['runBo'] = false;
        let _this = this;
        this.node.opacity = 0;
        this.map = this.mapNode.getComponent("Map");
        window['flagPoint'] = this.map.flagPoint;

        //在这里增加图块名，生成地面
        this.map.isHit = { "r0": true, "r1": true, "r4": true, "r5": true, "r6": true, "r7": true,//土块
        "r92":true,"r93":true,"r14":true,"t31":true,"t32":true,"t33":true,//石块
        "t37":true,"t38":true,"t39":true,"t40":true,"t41":true,"t42":true,//沙块
        "y89":true,"y90":true,"y91":true,"y92":true,//墙块
        "y82":true,"y83":true,"y84":true,"y85":true,//墙块
       };


        this.map.Init = function () {
            window['runBo'] = true;
            _this.node.parent = _this.map.getLayerNodeFun("人物层");
            _this.node.x = _this.node.y = 0;
            _this.node.opacity = 255;
        }
        this.loading.onLoad();
        this.loading.onBJ();
        this.loading.Init();
        this.loader();
        _this.loadLen += this.map.LoadLength();
        this.map.Loading = function (l, t) {
            _this.onLoadTxt();
        }
        let i=0;
        this.map.onLoadSprite = function (node, LayerName) {
            if (node.name == 'chongzi' || node.name == 'mogu' || node.name == 'yazi' || node.name == 'shitouguai' || node.name == 'goutou') {
                let gwcObj = { 'mogu': [1, 1], 'chongzi': [1, 1], 'yazi': [2, 2], 'shitouguai': [3, 1], 'goutou': [3, 3] }
                let newNode = cc.instantiate(_this.PrefabObj[node.name]);
                if (newNode != null) {
                    let js = newNode.addComponent('monster');
                    js.init(node.y + node.w3.y, 2);
                    newNode.parent = node.parent;
                    newNode.x = node.x;
                }
                _this.map.removeMapNode(node);
                node.destroy();
            }
        }

        this.mc = this.node.children[0].getComponent(dragonBones.ArmatureDisplay);
    }
    private loadCur = 0;
    private loadLen = 0;
    private onLoadTxt() {
        this.loadCur++;
        this.loading.setTxt(this.loadCur, this.loadLen);//
        if (this.loadCur >= this.loadLen) {
            this.loading.killPar();
        }
    }
    private PrefabObj;
    private loader() {
        let _this = this;
        this.PrefabObj = {};
        let arr = ['chongzi', 'mogu', 'yazi', 'shitouguai', 'goutou'];
        this.loadLen += arr.length;
        arr.map(v => {
            cc.loader.loadRes('Prefab/' + v, function (err, prefab) {
                if (!err) _this.PrefabObj[v] = cc.instantiate(prefab);
                _this.onLoadTxt();
            })
        })

    }
    private run() {
        if (window['xueInt'] <= 0) { return; }
        if (this.mcID == '待机' || this.mcID == '伤') {
            this.mcID = '跑';
        }
    }
    private onCollisionEnter(other, self) {
        if (other.tag == 1) {
            this.map.removeMapNode(other.node);
            if (this.jbArr.length > 0) {
                let jmc = this.jbArr[0];
                let animation = jmc.getComponent(cc.Animation);
                animation.play('coins');
                this.jbArr.splice(0, 1);
                let sou = jmc.getComponent(cc.AudioSource);
                sou.volume = 0.5;
                sou.play();
                if (this.jbArr.length == 0) {
                    this.jbArr[this.jbArr.length] = cc.instantiate(jmc);
                }
                let onFinished = function () {
                    this.jbArr[this.jbArr.length] = jmc;
                    jmc.parent = null;
                    animation.off('finished', onFinished, this);
                }
                animation.on('finished', onFinished, this);
                jmc.parent = this.node.parent;
                jmc.x = other.node.x + 22;
                jmc.y = other.node.y - 22;


            }
        } else if (other.tag == 6) {
            if (!this.world.pzbo && this.world.isDown()) {
                this.jump(this.bounce / 2, true);
            }
        }
    }
    private jump(i = null, bo = false) {

        if ((i != null && this.world.pzbo) || bo) {
            this.world.bounce = i;
            cc.audioEngine.play(this.jumpSou, false, 0.3);

        }
    }
    private mcID = "";
    private stand() {
        if (window['xueInt'] <= 0) { return; }
        if (this.mcID != '待机' && this.world.pzbo) {
            this.mcID = '待机';
        }
    }
    private onKeyPressed(keyCode, event) {
        if (window['xueInt'] <= 0) { return; }//
        switch (keyCode) {
            case cc.macro.KEY.a:
            case cc.macro.KEY.left:
                let sy = this.keyArr.indexOf("左");
                if (sy == -1) {
                    this.keyArr.unshift("左")
                }
                this.run();
                break;
            case cc.macro.KEY.d:
            case cc.macro.KEY.right:
                let sy2 = this.keyArr.indexOf("右");
                if (sy2 == -1) {
                    this.keyArr.unshift("右")
                }
                this.run();
                break;
            case cc.macro.KEY.k:
                //this.keyTiao();
                this.tiaoBo = true;
                break;
        }
    }
    private tiaoBo: boolean = false;
    private onKeyReleased(keyCode, event) {
        switch (keyCode) {
            case cc.macro.KEY.a:
            case cc.macro.KEY.left:
                let sy = this.keyArr.indexOf("左");
                if (sy != -1) {
                    this.keyArr.splice(sy, 1);
                }
                break;
            case cc.macro.KEY.d:
            case cc.macro.KEY.right:
                let sy2 = this.keyArr.indexOf("右");
                if (sy2 != -1) {
                    this.keyArr.splice(sy2, 1);
                }
                break;
            case cc.macro.KEY.k:
                //this.keyTiao();
                this.tiaoBo = false;
                break;
        }
    }
    private world: world
    start() {
        this.world = this.node.getComponent("world");
        let _this = this;
        this.world.hitHeadFun = function (id) {
            let n: cc.Node = _this.map.showNodeObj[id];
            if (n != null) {
                if (n.name == "问号" && n['currentFrame'] < n['totalFrame']) {
                    cc['tween'](n)
                        .by(0.1, { y: 5 })      // node.scale === 4 (2+2)
                        .by(0.1, { y: -5 })      // node.scale === 5
                        .start()

                    if (n['info'] == null || n['info'].type == null || n['info'].type == "出怪") {
                        let pn = window["pool"]["getPrefab"]("ygou");
                        if (pn != null) {
                            pn.x = n.x + 16;
                            pn.y = n.y + 2;
                            pn.parent = n.parent;
                            pn.zIndex = n.zIndex - 0.5;
                            pn.getComponent("world").bounce = 10;
                            //  pn["bomb"].Init();
                        }
                        n['gotoAndStop'](n['totalFrame']);
                    } else if (n['info'].type == "爆炸") {

                    }


                } else if (n.name == "p1") {
                    if (n.name == "p1") {

                    }
                }
            }

        }

        this.world.updateMapLocation = function () {
            let rect = _this.map.MapRect;
            if (rect == null) {
                return;//
            }
            let nx = 200;
            let ny = 150;
            let cp = new cc.Vec2(_this.node.x * -1 + nx, _this.node.y * -1 + ny);
           
            //区域限制
            if (rect.width > cc.view.getVisibleSize().width) {//
                if (_this.node.x < rect.x + nx) {
                    cp.x = rect.x * -1;
                }
                if (_this.node.x > rect.x + rect.width - (cc.view.getVisibleSize().width - nx)) {
                    cp.x = (rect.x + rect.width - cc.view.getVisibleSize().width) * -1;
                }
            } else {
                cp.x = rect.x * -1 + nx - rect.width / 2;
            }
            if (cp.x != _this.mapNode.x || cp.y != _this.mapNode.y) {
               
                if (_this.map == null) {
                    _this.node.x = cp.x;
                    _this.node.y = cp.y;
                } else {
                  
                    _this.map.setLocationFun(cp.x, cp.y);

                }
            }
        }
    }

    update(dt) {
        this.loading.onStart();
        if (this.tiaoBo) {
            this.jump(this.bounce);

        }
        if (this.mc.armatureName != '熊大' + this.mcID) {
            this.mc.armatureName = '熊大' + this.mcID;
            let mObj = { "跑": '熊大跑', '待机': 'newAnimation', '跳': '熊大跳', '伤': '熊大伤' }
            this.mc.playAnimation(mObj[this.mcID], 0)
        }
        this.world.pzbo = this.world.isJump();
        if (!this.world.pzbo && this.mcID != '跳') {
            this.mcID = '跳';
        } else if (this.world.pzbo && this.mcID == '跳') {
            if (this.keyArr[0] === "左" || this.keyArr[0] === "右") {
                this.mcID = '跑';
            } else {
                this.mcID = '待机';
            }
        }
        if (this.keyArr.length == 0) {
            this.stand();

        } else if (this.keyArr[0] === "左") {

            this.mcNode.scaleX = -1;
            this.world.setXY(this.node.x + this.speed * this.mcNode.scaleX);

        } else if (this.keyArr[0] === "右") {
            this.mcNode.scaleX = 1;
            this.world.setXY(this.node.x + this.speed * this.mcNode.scaleX);
        }
    }
}
